package no.group.gowther.rest;

import no.group.gowther.service.OnePieceTagService;
import no.group.gowther.service.dto.*;
import no.group.gowther.service.dto.param.TagCreateDTO;
import no.group.gowther.service.dto.param.TagQueryDTO;
import no.group.gowther.service.dto.param.TagRenameDTO;
import no.group.gowther.rest.vo.param.TagQueryParam;
import no.group.gowther.rest.vo.param.TagRenameParam;
import no.group.gowther.rest.vo.param.TagCreateParam;
import no.group.gowther.rest.vo.Result;
import no.group.gowther.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;

/**
 * @author ayatsuji
 * @date 2022-04-24 23:08
 * @since
 */
@Validated
@RestController
@RequestMapping("api/tag")
public class TagRestController {

    private final TagService tagService;

    @Autowired
    private OnePieceTagService onePieceTagService;

    public TagRestController(TagService tagService) {
        this.tagService = tagService;
    }

    @GetMapping("subTag")
    public Result<List<TagDTO>> querySubTag(Long tagId) {
        return Result.success(tagService.querySubTag(Optional.ofNullable(tagId)));
    }

    @GetMapping
    public Result<ListDTO<TagDTO>> queryTagFuzzily(@Validated TagQueryParam tagQueryParam) {
        TagQueryDTO tagQueryDTO = new TagQueryDTO(tagQueryParam);
        tagQueryDTO.setTagName(tagQueryParam.getFuzzyTagName());
        return Result.success(tagService.queryTagFuzzily(tagQueryDTO));
    }

    @PostMapping
    public Result<?> createTag(@RequestBody TagCreateParam tagCreateParam) {
        TagCreateDTO tagCreateDTO = new TagCreateDTO();
        tagCreateDTO.setParentTagId(tagCreateParam.getParentTagId());
        tagCreateDTO.setTagName(tagCreateParam.getTagName());
        tagService.create(tagCreateDTO);
        return Result.success();
    }

    @PutMapping("rename")
    public Result<?> rename(@RequestBody @Validated TagRenameParam tagRenameParam) {
        TagRenameDTO tagRenameDTO = new TagRenameDTO();
        tagRenameDTO.setId(tagRenameParam.getId());
        tagRenameDTO.setNewTagName(tagRenameParam.getNewTagName());
        tagService.rename(tagRenameDTO);
        return Result.success();
    }

    @DeleteMapping
    public Result<?> delete(@NotNull(message = "标签id不能为空") Long tagId) {
        tagService.delete(tagId);
        return Result.success();
    }

    @GetMapping("referNum")
    public Result<Long> referCount(@NotNull(message = "标签id不能为空") Long tagId) {
        return Result.success(onePieceTagService.countReferNum(tagId));
    }

    @GetMapping("{id}")
    public Result<TagDTO> queryTag(@PathVariable Long id) {
        return Result.success(tagService.queryTab(id));
    }
}
